<template>
  <a-modal
    v-model:visible="editModal.visible"
    width="600px"
    :title="editModal.title"
    :mask-closable="false"
    :keyboard="false"
    :centered="true"
    :body-style="{ maxHeight: 'calc(100vh - 200px)' }"
    @cancel="closeModal"
  >
    <a-card>
      <a-form ref="refForm" :model="form">
        <div>
          <a-form-item label="文件名称" name="fileName" :rules="[{ required: true, message: '请输入文件名称!' }]">
            <a-input v-model:value="form.fileName" :maxlength="64" allow-clear></a-input>
          </a-form-item>

          <a-form-item label="文件描述" name="fileDesc">
            <a-input v-model:value="form.fileDesc" :maxlength="64" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="文件数量" :rules="[{ required: true, message: '请选择文件数量!' }]" name="fileAmount">
            <a-input-number id="inputNumber" v-model:value="form.fileAmount" :min="0" :max="100" />
          </a-form-item>
          <a-form-item label="文件格式" :rules="[{ required: true, message: '请选择文件格式!' }]" name="fileFormat">
            <a-select v-model:value="form.fileFormat" mode="multiple">
              <a-select-option
                v-for="(item, index) in typeLimitList"
                :key="index"
                :disabled="item === 'txt' && form.signFlag"
                :value="item"
                >{{ item }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item
            label="是否必传文件"
            :rules="[{ required: true, message: '是否必传文件!' }]"
            name="newRequireFile"
          >
            <a-switch v-model:checked="form.newRequireFile"> </a-switch>
          </a-form-item>
          <a-form-item
            label="是否必填版本信息"
            :rules="[{ required: true, message: '是否必填版本信息!' }]"
            name="newRequireVersion"
          >
            <a-switch v-model:checked="form.newRequireVersion"> </a-switch>
          </a-form-item>
          <a-form-item
            v-if="taskType === 3"
            label="是否允许在启动会之前补齐"
            :rules="[{ required: true, message: '是否允许在启动会之前补齐!' }]"
            name="newComplementFile"
          >
            <a-switch v-model:checked="form.newComplementFile"> </a-switch>
          </a-form-item>
          <a-form-item label="模板文件">
            <MyUploadFile v-model:fileList="form.templateFileList" :show-file-list="true" />
          </a-form-item>
          <template v-if="source !== 'finance'">
            <a-form-item v-if="isInputFolder" label="文件归档路径">
              <a-input v-model:value="form.archiveFolderName" :maxlength="200" placeholder="请输入"></a-input>
            </a-form-item>
            <a-form-item v-else label="文件归档路径">
              <a-button type="primary" @click="handleSelect">选择</a-button>
              <div class="mt-2">{{ form.pathName }}</div>
            </a-form-item>
          </template>
        </div>
        <div v-if="!hideSignSetting" class="dashed-line"></div>
        <div v-if="!hideSignSetting" class="m-t-20">
          <a-form-item
            :style="form.fileFormat.includes('txt') || orgInfo.esignFlag === 0 ? 'margin-bottom: 0' : ''"
            label="是否需要电子签署"
            name="signFlag"
          >
            <a-switch
              v-model:checked="form.signFlag"
              :disabled="form.fileFormat.includes('txt')"
              :checked-value="1"
              :un-checked-value="0"
            ></a-switch>
          </a-form-item>
          <div
            v-if="orgInfo.esignFlag === 0"
            class="error"
            style="display: inline-block; vertical-align: top; margin-left: 10px"
          >
            <InfoCircleOutlined style="width: 20px; margin: 1px 5px 0 0" />
            <span style="vertical-align: top">本组织未开启电子签署，暂不支持使用此功能，请联系组织管理员</span>
          </div>
          <div
            v-if="form.fileFormat.includes('txt')"
            class="error"
            style="display: inline-block; vertical-align: top; margin-left: 10px"
          >
            <InfoCircleOutlined style="width: 20px; margin: 1px 5px 0 0" />
            <span style="vertical-align: top">txt文件不可开启电子签署</span>
          </div>
          <a-form-item
            v-if="form.signFlag"
            label="电子签署方式"
            name="signWay"
            :rules="[{ required: !!form.signFlag, message: '请选择签署方式!' }]"
          >
            <a-checkbox-group v-model:value="form.signWay">
              <a-checkbox value="1">个人签名</a-checkbox>
              <a-checkbox value="2">组织签章</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
          <div class="warning-text">
            （1）电子签名主体人员请在“流程配置”中的审批节点进行设置；
            <br />
            （2）组织签章将在所有审批节点完成后，再流转至机构秘书处进行签章，签章完成后流程结束；
          </div>
        </div>
      </a-form>
    </a-card>
    <template #footer>
      <div>
        <a-button @click="closeModal">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleSubmit">保存</a-button>
      </div>
    </template>
  </a-modal>
  <SelectAchiveFolder
    ref="refSelectFolder"
    title-str="选择归档路径"
    :tree-data-list="treeDataList"
    @onGetArchiveFolderId="getArchiveFolderId"
  ></SelectAchiveFolder>
</template>
<script lang="ts" setup>
import { reactive, ref, Ref } from 'vue'
import { getCtmsArchiveFolder, getArchiveFolderByProjectType } from '@@/api/project/documentManage'
import SelectAchiveFolder from './SelectAchiveFolder.vue'
import { PTgetById } from '@@/api/progresstemplate'
import { initForm } from '../index'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import { InfoCircleOutlined } from '@vicons/antd'
import { storage } from '@/utils/Storage'
const route = useRoute()
const emits = defineEmits(['onReloadTable'])
const {
  taskId,
  speedId,
  updateFn,
  addFn,
  taskType,
  isNeedSelectFolder = true,
  hideSignSetting,
  tag,
  isByProjectType,
  projectType,
  noDataMsg,
  isInputFolder
} = defineProps<{
  taskId: string
  speedId?: string | null | undefined
  updateFn: any
  addFn: any
  taskType: any
  source?: string
  isNeedSelectFolder: boolean
  hideSignSetting?: boolean
  tag?: number | string
  isByProjectType?: any
  projectType?: any
  noDataMsg?: string
  isInputFolder?: boolean
}>()
const orgInfo = storage.get('ORGINFO')

const typeLimitList = ['pdf', 'doc/docx', 'ppt/pptx', 'xls/xlsx', 'txt', 'jpg/png']
const editModal = reactive({
  visible: false,
  title: ''
})
const form = ref<any>(initForm())
const refForm = ref()
const loading = ref(false)
const closeModal = () => {
  form.value = initForm()
  editModal.visible = false
}
// 获取归档文档id
const getArchiveFolderId = ({ checkedKey, pathName }) => {
  form.value.speedFolderId = checkedKey
  form.value.archiveFolderId = checkedKey
  form.value.pathName = pathName
}
const handleSubmit = async () => {
  const valid = await refForm.value.validate()
  if (valid) {
    loading.value = true
    form.value.taskId = taskId
    form.value.tag = tag
    if (form.value.newRequireFile) {
      form.value.requireFile = 1
    } else {
      form.value.requireFile = 0
    }
    if (form.value.newRequireVersion) {
      form.value.requireVersion = 1
    } else {
      form.value.requireVersion = 0
    }
    // 候补文件
    if (form.value.newComplementFile) {
      form.value.complementFile = 1
    } else {
      form.value.complementFile = 0
    }
    // 如果任务类型不为立项申请
    if (taskType !== 3) {
      form.value.complementFile = 0
    }
    if (!form.value.signFlag) {
      form.value.signWay = []
    }
    if (form.value.templateFileList && form.value.templateFileList.length) {
      form.value.templateFileList.forEach((item: any) => {
        item.tempFileId = item.uid
        item.tempFileName = item.name
      })
    }
    form.value.templateFile = JSON.stringify(form.value.templateFileList || [])
    if (editModal.title === '新增文件清单') {
      addFn(form.value)
        .then(() => {
          loading.value = false
          emits('onReloadTable')
          closeModal()
        })
        .catch(() => {
          loading.value = false
        })
    } else {
      updateFn(form.value)
        .then(() => {
          loading.value = false
          emits('onReloadTable')
          closeModal()
        })
        .catch(() => {
          loading.value = false
        })
    }
  }
}
const treeDataList: Ref<any> = ref([])
// 获取树数据
const reloadTreeData = () => {
  getCtmsArchiveFolder({ projectId: sessionStorage.getItem('__projectId') })
    .then((res) => {
      treeDataList.value = res ? [res] : []
      addFolderKey(treeDataList.value, 'archiveFolderId')
    })
    .catch(() => {})
}
const refSelectFolder = ref()

const handleSelect = () => {
  if (!treeDataList.value || !treeDataList.value.length) {
    return message.warning(noDataMsg || '请先选择文件夹目录')
  }
  refSelectFolder.value.show(form.value)
}

// 添加树组件所需的key
const addFolderKey = (list, key) => {
  list.forEach((item) => {
    if (item[key]) {
      item.folderKey = item[key]
    }
    if (item.children && item.children.length) {
      addFolderKey(item.children, key)
    }
  })
}

// sop获取项目文件夹目录模板的目录
const getSpeedDeital = () => {
  PTgetById({
    speedId: speedId
  }).then((res) => {
    treeDataList.value = res.folder ? [res.folder] : []
    addFolderKey(treeDataList.value, 'speedFolderId')
  })
}

const getTreeData = () => {
  getArchiveFolderByProjectType({
    projectType: projectType
  }).then((res) => {
    treeDataList.value = res.folder ? [res.folder] : []
    addFolderKey(treeDataList.value, 'projectFolderId')
  })
}

const show = (data, type) => {
  if (isNeedSelectFolder && !isInputFolder) {
    if (route.path === '/sop/progressTemplate/index' || route.path === '/configure/progress/index') {
      // sop-进度
      getSpeedDeital()
    } else if (isByProjectType) {
      getTreeData()
    } else {
      // 项目-进度
      reloadTreeData()
    }
  }

  if (type === 'edit') {
    form.value = JSON.parse(JSON.stringify(data))
    if (form.value.requireFile === 1) {
      form.value.newRequireFile = true
    } else {
      form.value.newRequireFile = false
    }
    if (form.value.requireVersion === 1) {
      form.value.newRequireVersion = true
    } else {
      form.value.newRequireVersion = false
    }
    // 候补文件
    if (form.value.complementFile === 1) {
      form.value.newComplementFile = true
    } else {
      form.value.newComplementFile = false
    }
    if (form.value.templateFile) {
      form.value.templateFileList = JSON.parse(form.value.templateFile)
      form.value.templateFileList.forEach((ele: any) => {
        ele.uid = ele.tempFileId
        ele.name = ele.tempFileName
      })
    } else {
      form.value.templateFileList = []
    }

    editModal.title = '编辑文件清单'
  } else {
    editModal.title = '新增文件清单'
    form.value.displayOrder = data
  }
  editModal.visible = true
}
defineExpose({
  show
})
</script>
<style scoped lang="less">
.m-t-20 {
  margin-top: 20px;
}
</style>
